package com.schoolvisitors.controller.user;

import com.alibaba.fastjson2.JSONObject;
import com.schoolvisitors.entity.Admin;
import com.schoolvisitors.entity.Room;

import com.schoolvisitors.entity.TimeSlot;
import com.schoolvisitors.enums.PermissionEnum;
import com.schoolvisitors.enums.RoomTypeEnum;
import com.schoolvisitors.response.ResultBody;
import com.schoolvisitors.service.AdminPermissionService;
import com.schoolvisitors.service.CubicleService;
import com.schoolvisitors.service.RoomService;
import com.schoolvisitors.service.TimeSlotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/v1/user")
public class UserRoomController {

    private final RoomService roomService;
    private final TimeSlotService timeSlotService;
    private final CubicleService cubicleService;
    private final AdminPermissionService adminPermissionService;

    public UserRoomController(RoomService roomService, TimeSlotService timeSlotService, CubicleService cubicleService, AdminPermissionService adminPermissionService) {
        this.roomService = roomService;
        this.timeSlotService = timeSlotService;
        this.cubicleService = cubicleService;
        this.adminPermissionService = adminPermissionService;
    }

    @GetMapping("/getRooms")
    public ResultBody getRooms() {
        List<Room> rooms = roomService.getRooms();
        JSONObject data = new JSONObject();

        return ResultBody.success(rooms);
    }

    @GetMapping("/getGroupRoomsByFloor")
    public ResultBody getGroupRoomsByFloor() {
        Map<Long, List<Room>> rooms = roomService.getGroupRoomsByFloorId();
        JSONObject data = new JSONObject();

        return ResultBody.success(rooms);
    }

    @GetMapping("/getRoomInfo")
    public ResultBody getRoomInfo(@RequestParam("roomId") Long roomId) {
        JSONObject result = new JSONObject();

        Room room = roomService.getRoom(roomId);
        result.put("room", room);

        List<TimeSlot> timeSlotRules = timeSlotService.getAllTimeSlots();
        result.put("timeSlot", timeSlotRules);

        PermissionEnum permission = room.getType() == RoomTypeEnum.LAB ? PermissionEnum.LAB_REVIEW : PermissionEnum.MEETING_REVIEW;

        // 通过权限服务获取有权限的审核人列表
        List<Admin> reviewers = adminPermissionService.getReviewers(room, permission);
        log.info("reviewers{}", reviewers);


        List<Map<String, String>> reviewerList = new ArrayList<>();

        for (Admin admin : reviewers) {
            Map<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(admin.getId()));
            map.put("name", admin.getRealName());
            reviewerList.add(map);
        }
        result.put("reviewer", reviewerList);

        return ResultBody.success(result);
    }




}
